<template>
  <div class="page-miH page-bgBack">
    <div class="flex-center-between mh20 pt24">
      <a-space>
        <a-button type="primary" @click="goAdd"> <a-icon type="plus" />新增工资表模板</a-button>
      </a-space>
      <a-button v-if="isAdmin" type="primary" @click="showIssueModal"> 下发工资表模板 </a-button>
    </div>
    <div class="p16">
      <a-table :columns="columns" :pagination="false" row-key="id" :loading="loading" :data-source="data">
        <template slot="gongziItems" slot-scope="text">
          <a-tooltip :title="text">{{ text }}</a-tooltip>
        </template>
        <template slot="tongjiItems" slot-scope="text">
          <a-tooltip :title="text">{{ text }}</a-tooltip>
        </template>
        <template slot="groupItems" slot-scope="text">
          <a-tooltip :title="text">{{ text }}</a-tooltip>
        </template>
        <a slot="action" slot-scope="text, record" class="tc-theme" style="margin-left: -10px">
          <span @click="goEdit(record)">查看</span>
          <a-divider type="vertical" />
          <span>
            <a-popconfirm :title="'确定删除' + record.name + '?'" @confirm="deleteSalaryTemplatesList(record)">
              <a-icon slot="icon" type="question-circle-o" style="color: red" />
              <a href="#" :disabled="record.name === '默认模板' || record.name === '计时制模板'">删除</a>
            </a-popconfirm>
          </span>
        </a>
      </a-table>
    </div>
    <a-modal
      :visible="issueModalVisible"
      title="下发工资模板"
      width="538px"
      :destroy-on-close="true"
      @ok="confirmIssueModal"
      @cancel="handleCancelIssueModal"
    >
      <a-row>
        <a-col :span="12">
          <span>请选择工资模板</span>
          <a-select
            v-model="contractList"
            mode="multiple"
            placeholder="请选择工资模板"
            option-filter-prop="children"
            show-search
            :filter-option="filterOption"
            style="width: 240px; margin-top: 10px"
          >
            <a-select-option v-for="(item, index) in contractData" :key="index" :value="item.id">
              <a-tooltip placement="left" :title="item.name">
                {{ item.name }}
              </a-tooltip>
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="12">
          <span>请选择下发用工单位</span>
          <a-tree-select
            v-model="companyList"
            :treeData="companyTreeWithUuid"
            :replaceFields="{
              children: 'companyList',
              title: 'name',
              key: 'uuid',
              value: 'uuid'
            }"
            treeCheckable
            showSearch
            treeNodeFilterProp="title"
            placeholder="请选择用工单位"
            style="width: 240px; margin-top: 10px; max-height: 350px; overflow: auto"
          />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import { deleteSalaryTemplates, batchDeleteSalary } from "@/api/wages/template";
import { getNotArchiveById } from "@/api/wages/monthly";
import { isContainByString } from "@/utils/index";
import { saveIssuedSeal } from "./api";
const columnsInit = [
  {
    title: "模板名称",
    dataIndex: "name",
    width: 200,
    ellipsis: true
  },
  {
    title: "工资项",
    dataIndex: "gongziItems",
    width: 300,
    ellipsis: true,
    scopedSlots: { customRender: "gongziItems" }
  },
  {
    title: "统计项",
    dataIndex: "tongjiItems",
    width: 300,
    ellipsis: true,
    scopedSlots: { customRender: "tongjiItems" }
  }
];
export default {
  data() {
    return {
      loading: true,
      columns: [],
      data: [],
      companyId: this.$store.state.hr.companyId,
      // modal显示隐藏
      issueModalVisible: false,
      // 下发选择框合同数据
      contractData: [],
      // 已选的合同模板数据
      contractList: [],
      // 已选的公司数据
      companyList: []
    };
  },
  computed: {
    isAdmin() {
      return isContainByString("contractAdmin");
    },
    companyTreeWithUuid() {
      return this.$store.state.site.companyTreeWithUuid;
    },
    companyUuidDict() {
      return this.$store.state.site.companyUuidDict;
    }
  },
  watch: {
    companyTreeWithUuid: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.companyList = JSON.parse(JSON.stringify(this.companyList));
        }
      },
      immediate: true
    }
  },
  created() {
    this.getTemplatesList();

    const columnsTemp = [...columnsInit];
    if (!this.isAdmin) {
      columnsTemp.push({
        title: "适用薪资组",
        dataIndex: "groupItems",
        width: 200,
        ellipsis: true,
        scopedSlots: { customRender: "groupItems" }
      });
    }
    this.columns = [
      ...columnsTemp,
      {
        title: "操作",
        dataIndex: "action",
        width: 100,
        scopedSlots: { customRender: "action" }
      }
    ];
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    deleteSalaryTemplatesList(record) {
      getNotArchiveById({ salaryTemplateId: record.id }).then((res) => {
        if (res.data) {
          var arr = [];
          res.data.forEach((item, index) => {
            arr.push(item.monthly);
          });
          arr = arr.join(",");
          var idList = [];
          res.data.forEach((item, index) => {
            idList.push(item.id);
          });
          const _this = this;
          this.$confirm({
            okText: "确定",
            cancelText: "取消",
            title: `该模板已在${arr}月创建月工资表，删除模板会同时删除未归档的月工资表，仍旧继续吗？`,
            onOk() {
              deleteSalaryTemplates(record.id).then(({ success }) => {
                if (success) {
                  _this.$notification["success"]({ message: "删除成功" });
                  _this.getTemplatesList();
                }
              });
              batchDeleteSalary(idList).then(({ success }) => {});
            }
          });
        } else {
          deleteSalaryTemplates(record.id).then(({ success }) => {
            if (success) {
              this.$notification["success"]({ message: "删除成功" });
              this.getTemplatesList();
            }
          });
        }
      });
    },
    getTemplatesList() {
      this.loading = true;
      this.$request({
        url: `/salary/api/v1/salaryTemplates/selectByCompanyIdNew`,
        params: {
          companyId: this.isAdmin ? "0" : this.companyId
        }
      }).then((res) => {
        this.loading = false;
        this.data = res.data.map((item) => {
          const gzItems = item.wageItemVOList ? item.wageItemVOList.map((li) => li.name) : [];
          const tjItems = item.templateCovarianceItemVOList ? item.templateCovarianceItemVOList.map((li) => li.name) : [];
          const groupItems = item.salaryGroupVOList ? item.salaryGroupVOList.map((li) => li.name) : [];
          return {
            ...item,
            gongziItems: gzItems.join("，"),
            tongjiItems: tjItems.join("，"),
            groupItems: groupItems.join("，")
          };
        });
        this.contractData = res.data;
      });
    },
    goAdd() {
      this.$router.push({
        path: `/${this.isAdmin ? "contractAdmin" : "wages"}/gongzibiaomuban/edit`
      });
    },
    goEdit(record) {
      localStorage.setItem("xinzimubanTemp", JSON.stringify(record));
      this.$router.push({
        path: `/${this.isAdmin ? "contractAdmin" : "wages"}/gongzibiaomuban/edit`,
        query: {
          id: record.id
        }
      });
    },
    saveIssuedSeal() {
      if (this.companyList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的公司"
        });
        return;
      }
      if (this.contractList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的合同模板"
        });
        return;
      }
      const data = {
        companyId: this.companyList((li) => this.companyUuidDict[li]),
        salaryTemplateIds: this.contractList
      };
      saveIssuedSeal(data)
        .then((res) => {
          this.issueModalVisible = false;
          this.$notification["success"]({
            message: "成功",
            description: "下发成功"
          });
          this.companyList = [];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 方法
    confirmIssueModal() {
      // TODO 下发接口
      this.saveIssuedSeal();
    },
    handleCancelIssueModal() {
      this.issueModalVisible = false;
      // 已选的合同模板数据
      this.contractList = [];
      // 已选的公司数据
      this.companyList = [];
    },
    showIssueModal() {
      this.issueModalVisible = true;
    }
  }
};
</script>
<style lang="scss" scoped></style>
